package com.edu.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.demo.entity.*;
import com.edu.demo.pojo.AjaxResult;
import com.edu.demo.service.IConclusionService;
import com.edu.demo.service.IContractService;
import com.edu.demo.service.IProjectService;
import com.edu.demo.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.*;
import java.util.stream.Collectors;

/**结题表 前端控制器
 * </p>
 *
 * @author jixuewei
 * @since 2023-01-12
 */
@RestController
@RequestMapping("/conclusion")
public class ConclusionController {

    @Autowired
    private IConclusionService conclusionService;


    @Autowired
    private IProjectService projectService;

    @Autowired
    private IContractService contractService;

    /**
     * 学生上传或更新结题报告
     * @param conclusion
     * @return
     */
    @PostMapping("/upload")
    @PreAuthorize("@ps.hasPerm('stu:conclusion:save')")
    public AjaxResult saveOrUpdate(@RequestBody Conclusion conclusion){
        Student student = SecurityUtils.getStudent();
        QueryWrapper<Conclusion> updateWrapper = new QueryWrapper<>();
        updateWrapper.eq("project_id",conclusion.getProjectId());
        List<Conclusion> list = conclusionService.list(updateWrapper);
        if(list.isEmpty()){
            conclusion.setStuId(student.getId());
            conclusion.setStuName(student.getName());
            conclusion.setUploadTime(new Date());

            if(conclusionService.save(conclusion))
                return AjaxResult.success();
            return AjaxResult.error("提交失败");
        }

        conclusion.setUpdateStuId(student.getId());
        conclusion.setUpdateStuName(student.getName());
        conclusion.setUpdateTime(new Date());
        boolean update = conclusionService.update(conclusion, updateWrapper);
        if(update) return AjaxResult.success("更新成功");
        return AjaxResult.error("更新失败");
    }


    /**
     * 教师评阅更新结题报告
     * @param conclusion
     * @return
     */
    @PostMapping("/check")
    @PreAuthorize("@ps.hasPerm('tea:conclusion:check')")
    public AjaxResult teacherUpdate(@RequestBody Conclusion conclusion)
    {
        conclusion.setStatus((byte)1);
        boolean b = conclusionService.updateById(conclusion);
        if(b) return AjaxResult.success();
        return AjaxResult.error("更新失败");
    }


    /**
     * 超级管理员提交结题证明
     * @param conclusion
     * @return
     */
    @PostMapping("/through")
    @PreAuthorize("@ps.hasPerm('admin:conclusion:update')")
    public AjaxResult throughConclusion(@RequestBody Conclusion conclusion){
        SysUser sysUser = SecurityUtils.getSysUser();
        conclusion.setAdminId(sysUser.getId());
//        conclusionService.getById()
        boolean b = conclusionService.updateById(conclusion);
        if(b) {
            QueryWrapper<Contract> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("project_id",conclusion.getProjectId());
            Contract entity = new Contract();
            entity.setStatus((byte)1);//已完成项目但是未支付
            contractService.update(entity, updateWrapper);
            return AjaxResult.success();
        }
        return AjaxResult.error("服务出错");
    }


    /**
     * 管理员查询教师通过的项目
     */
    @PostMapping("/list")
    @PreAuthorize("@ps.hasPerm('admin:conclusion:list')")
    public AjaxResult listWhereIsThrough(){
        QueryWrapper<Conclusion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("through",1);
        queryWrapper.isNull("prove");
        List<Conclusion> conclusions = conclusionService.list(queryWrapper);
        List<Integer> projectIds = conclusions.stream().map(Conclusion::getProjectId).collect(Collectors.toList());
        List<Project> projectList = projectService.listByIds(projectIds);
        conclusions.forEach(conclusion -> {
            for (Project project : projectList) {
                if(conclusion.getProjectId()==project.getId()) conclusion.setProject(project);
            }
        });

        Collections.reverse(conclusions);
        return AjaxResult.success(conclusions);
    }

    /**
     * 学生查看项目结题
     * @param projectId
     * @return
     */
    @GetMapping("/query/my")
    @PreAuthorize("@ps.hasPerm('stu:conclusion:query')")
    public AjaxResult queryStudentConclusion(@RequestParam Integer projectId){
        QueryWrapper<Contract> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id",projectId);
        queryWrapper.in("status", Arrays.asList(1,2,0)); //查询该项目的且正常状态的合同
        List<Contract> list = contractService.list(queryWrapper);
        Student student = SecurityUtils.getStudent();
        boolean flag = false;
        for (Contract contract : list) {  //判断该项目的合同是否有该学生
            if(contract.getStuId() == student.getId()){
                flag = true;
            }
        }
        if(flag){
            List<Conclusion> conclusions = conclusionService.list(new QueryWrapper<Conclusion>().eq("project_id", projectId));

            return AjaxResult.success(conclusions);
        }


        return AjaxResult.error("只能查看自己参与的项目");
    }


    /**
     * 查询某个项目的结题报告
     * @param project
     * @return
     */
    @GetMapping("/one")
    @PreAuthorize("@ps.hasPerm('sys:conclusion:query')")
    public AjaxResult getOne(@RequestParam Integer project){
        QueryWrapper<Conclusion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id",project);
        Conclusion one = conclusionService.getOne(queryWrapper);
        if(one==null) return AjaxResult.error("没有该项目的结题信息");
        return AjaxResult.success(one);
    }


}
